#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unicode 测试脚本
测试各种 Unicode 字符的显示和输出
"""

import sys
import platform

def setup_unicode():
    """设置 Unicode 环境"""
    if platform.system() == 'Windows':
        try:
            import ctypes
            ctypes.windll.kernel32.SetConsoleOutputCP(65001)
            ctypes.windll.kernel32.SetConsoleCP(65001)
        except Exception as e:
            print(f"Warning: Could not set console code page: {e}")

    # 设置 Python 输出编码
    if hasattr(sys.stdout, 'reconfigure'):
        sys.stdout.reconfigure(encoding='utf-8', errors='backslashreplace')
    if hasattr(sys.stderr, 'reconfigure'):
        sys.stderr.reconfigure(encoding='utf-8', errors='backslashreplace')

def test_basic_unicode():
    """测试基本 Unicode 字符"""
    print("=== 基本 Unicode 字符测试 ===")

    tests = [
        ("ASCII", "Hello World"),
        ("中文", "你好世界"),
        ("日文", "こんにちは"),
        ("韩文", "안녕하세요"),
        ("俄文", "Привет"),
        ("阿拉伯文", "مرحبا"),
        ("泰文", "สวัสดี"),
        ("Emoji", "✅ 🎉 🚀 ⭐ 💡"),
        ("数学符号", "∑ ∫ √ π ∞ ≠ ≈"),
        ("货币符号", "$ € £ ¥ ₩ ₽"),
        ("箭头符号", "← ↑ → ↓ ↔ ↕"),
        ("技术符号", "© ® ™ ° † ‡ • …"),
    ]

    for name, text in tests:
        try:
            print(f"  {name}: {text}")
        except UnicodeEncodeError as e:
            print(f"  {name}: ERROR - {e}")

    print()

def test_emoji_categories():
    """测试不同类别的 Emoji"""
    print("=== Emoji 分类测试 ===")

    emoji_categories = {
        "表情": ["😀 😃 😄 😁 😆 😅 😂 🤣 😊 😇"],
        "手势": ["👍 👎 👌 ✌️ 🤞 🤟 🤘 🤙 👈 👉"],
        "动物": ["🐶 🐱 🐭 🐹 🐰 🦊 🐻 🐼 🐨 🐯"],
        "食物": ["🍎 🍐 🍊 🍋 🍌 🍉 🍇 🍓 🫐 🍈"],
        "交通": ["🚗 🚕 🚙 🚌 🚎 🏎️ 🚓 🚑 🚒 🚐"],
        "符号": ["❤️ 🧡 💛 💚 💙 💜 🖤 🤍 🤎 💔"],
    }

    for category, emojis in emoji_categories.items():
        try:
            print(f"  {category}: {' '.join(emojis)}")
        except UnicodeEncodeError as e:
            print(f"  {category}: ERROR - {e}")

    print()

def test_chinese_text():
    """测试中文文本"""
    print("=== 中文文本测试 ===")

    chinese_texts = [
        "简体中文：你好世界",
        "繁體中文：你好世界",
        "中文标点：，。！？；：""''（）【】《》",
        "中文数字：一二三四五六七八九十百千万亿",
        "中文成语：画蛇添足、亡羊补牢、守株待兔",
        "诗词：床前明月光，疑是地上霜。举头望明月，低头思故乡。",
        "网络用语：点赞、吐槽、围观、给力、神马都是浮云",
    ]

    for text in chinese_texts:
        try:
            print(f"  {text}")
        except UnicodeEncodeError as e:
            print(f"  ERROR: {e}")

    print()

def test_file_operations():
    """测试文件操作的 Unicode 支持"""
    print("=== 文件操作测试 ===")

    test_filename = "unicode_test_测试_🎉.txt"
    test_content = """这是一个 Unicode 测试文件
This is a Unicode test file
🎉 ✅ 🚀 你好世界
Hello World
"""

    try:
        # 写入文件
        with open(test_filename, 'w', encoding='utf-8') as f:
            f.write(test_content)
        print(f"✅ 写入文件成功: {test_filename}")

        # 读取文件
        with open(test_filename, 'r', encoding='utf-8') as f:
            read_content = f.read()
        print(f"✅ 读取文件成功")
        print(f"  文件内容预览: {read_content[:50]}...")

        # 删除测试文件
        import os
        os.remove(test_filename)
        print(f"✅ 删除测试文件成功")

    except Exception as e:
        print(f"❌ 文件操作失败: {e}")

    print()

def test_environment_info():
    """显示环境信息"""
    print("=== 环境信息 ===")
    print(f"  Python 版本: {sys.version}")
    print(f"  操作系统: {platform.system()} {platform.release()}")
    print(f"  平台: {platform.platform()}")
    print(f"  默认编码: {sys.getdefaultencoding()}")
    print(f"  文件系统编码: {sys.getfilesystemencoding()}")

    if hasattr(sys.stdout, 'encoding'):
        print(f"  标准输出编码: {sys.stdout.encoding}")
    if hasattr(sys.stderr, 'encoding'):
        print(f"  标准错误编码: {sys.stderr.encoding}")

    print()

def main():
    """主函数"""
    print("🚀 Unicode 测试工具")
    print("=" * 50)
    print()

    # 设置 Unicode 环境
    setup_unicode()

    # 显示环境信息
    test_environment_info()

    # 运行各种测试
    test_basic_unicode()
    test_emoji_categories()
    test_chinese_text()
    test_file_operations()

    print("🎉 Unicode 测试完成！")
    print()
    print("💡 如果所有测试都正常显示，说明你的环境支持 Unicode！")
    print("⚠️  如果看到乱码或错误，请运行 fix_unicode.ps1 脚本进行修复。")

if __name__ == "__main__":
    main()